Try Statement

Used to handle RuntimeException errors prior to the Exception Block.


Syntax

Try

//REALbasic statements

Catch [ErrorParameter] [As ErrorType]

//exception handlers

[ Finally]

//code that executes even if runtime exceptions were raised

End [Try]

PartDescription
ErrorParameter Optional, used to determine the type of runtime exception.
ErrorType Optional, if used, it must be used with ErrorParameter. Used to 'catch' a particular type of runtime error. If used, the Try block will handle only that type of runtime error.


Notes

The Try block is similar to the Exception block. Exceptions that occur within the Try block are caught by the Catch statement. It has the same syntax as the Exception statement. See the RuntimeException statement or the Runtime Errors theme for descriptions of each type of runtime error.

Unlike the Exception block, Try blocks can be nested. If a Try block does not handle an exception or re-raises it, it can be handled by the next outermost Try block, or by the Exception block itself if there are no containing Try blocks.

A Try block can contain its own Finally statement. The code in the Finally block will execute regardless of whether or not an exception was raised within the Try block.


Example

This example uses the Catch statement in a window's Open event handler to handle out of memory exceptions when trying to draw an imported gif image. The variable myPicture is a global property of type Picture. The picture "Logo" has been added to the Project Editor.

Sub Open
Try
 myPicture= New Picture(Logo.width,Logo.height,32)
 myPicture. Graphics.DrawPicture Logo,0,0

  Catch err as OutOfMemoryException
   MsgBox "Insufficient memory to draw the picture!"
End Try

The following example handles an attempt to access a nonexistent value in a Dictionary.

Try
 someValue =myDict.Value("doesn't exist")
Catch err as KeyNotFoundException
  MsgBox "The requested key does not exist."
End Try

See Also

Exception block; Catch, Finally, Function, Raise, Sub statements; RuntimeException class.